package com.fjycnet.eventbus;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.orangelife.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * EventBus学习使用
 * Created by ZeroVoid on 2018-6-15.
 */

public class _TestEventBusActivity extends AppCompatActivity {

    private TextView tvMsg;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_my_eventbus);
        tvMsg = findViewById(R.id.tvMsg);
        setListener();
        registerEventBus();
    }

    /**
     * 1 注册EventBus
     */
    private void registerEventBus() {
        EventBus.getDefault().register(this);
    }

    //2 解绑EventBus
    private void unregisterEventBus() {
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //2 解绑EventBus
        unregisterEventBus();
    }

    //3 订阅消息 threadMode priority
    @Subscribe(threadMode = ThreadMode.POSTING, priority = 5)
    public void readMessageFirst(MyMessageEvent event) {
        tvMsg.setText(event.getMessage());
        Toast.makeText(this, "收到消息", Toast.LENGTH_LONG).show();
    }

    //跳转到新的界面
    private void jumpOtherActivity() {
        Intent intent = new Intent(getApplicationContext(),
                EbSecondActivity.class);
        startActivity(intent);
    }

    private void setListener() {
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jumpOtherActivity();
            }
        });
    }
}
